package org.example.JDBC;

import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.sql.*;
import java.util.Properties;

public class DBUtil {
    private static volatile DataSource dataSource = null;

    /**
     * @return
     * @throws SQLException
     */
    private static DataSource getDataSource() throws SQLException {
        if (dataSource == null) {
            synchronized (DBUtil.class) {
                if (dataSource == null) {
                    InputStream in = DBUtil.class.getClassLoader().getResourceAsStream("config.properties");
                    Properties properties = new Properties();
                    try {
                        //从配置文件中读取配置信息
                        properties.load(in);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                    dataSource = new MysqlDataSource();
                    //配置数据源
                    ((MysqlDataSource) dataSource).setURL(properties.getProperty("url"));
                    ((MysqlDataSource) dataSource).setUser(properties.getProperty("user"));
                    ((MysqlDataSource) dataSource).setPassword(properties.getProperty("password"));
                }
            }
        }
        return dataSource;
    }

    /**
     *
     * @return
     */
    public static Connection getConnection() throws SQLException {
        getDataSource();
        return dataSource.getConnection();
    }

    /**
     *
     * @param connection
     * @param preparedStatement
     */
    public static void Clear(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet){
        if(resultSet!=null){
            try{
                resultSet.close();
            }catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(preparedStatement!=null){
            try {
                preparedStatement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(connection!=null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static <T>void Fill(Class clazz,T t ,ResultSet resultSet) throws SQLException, IllegalAccessException {
        ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
        int columnCount = resultSetMetaData.getColumnCount();
        Field[] fields = clazz.getDeclaredFields();
        for(int i=0;i<columnCount;i++){
            String columnName = resultSetMetaData.getColumnLabel(i+1);
            Object o=resultSet.getObject(columnName);
            fields[i].setAccessible(true);
            fields[i].set(t,o);
        }
    }
}
